package cn.kgc.springmvc.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: mosin
 * @version: v1.0  2022/10/19
 * 自定义拦截器 实现非法请求的拦截
 */
public class MyInterceptor implements HandlerInterceptor {

    // 到达用户请求的目标handler之前执行的方法   boolean  true  放行

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("请求被拦截，执行preHandle");

        // 判定用户的状态   是否是合法用户  登录
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        if(user!=null){
            // 放行请求
            return true;
        }

        // 跳转页面到登录页
        response.sendRedirect(request.getContextPath()+"/login.jsp");
        //请求拦截
        return false;
    }

    // 执行用户请求的目标handler之后执行的方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("请求被处理后，执行postHandle");
    }

    // 页面渲染完成后执行的方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("页面渲染完成后，afterCompletion");

    }
}
